package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.progressindicator.CircularProgressIndicator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LikeOrStarFragment extends Fragment {
    RecyclerView recyclerView;
    TextView btnLike,
            btnStar;
    CircularProgressIndicator progressIndicator;
    List<Article> articleLikeList;
    List<Article> articleStarList;
    String getLikeArticleUrl = SeverURL.URL + "/get_like_article";
    String getStarArticleUrl = SeverURL.URL + "/get_star_article";
    String state;
    LikeOrStartAdapter adapter;

    public LikeOrStarFragment(String type) {
        // Required empty public constructor
        this.state = type;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_like_or_star, container, false);

        initViews(view);
        initData();
        loadArticles(state);

        return view;
    }

    private void initData() {
        btnLike.setOnClickListener(v -> {
            progressIndicator.setVisibility(View.VISIBLE);
            getLikeOrStartArticles(getLikeArticleUrl, "like");
            //切换adapter
            loadArticles("like");
        });

        btnStar.setOnClickListener(v -> {
            progressIndicator.setVisibility(View.VISIBLE);
            getLikeOrStartArticles(getStarArticleUrl, "star");
            //切换adapter
            loadArticles("star");
        });

    }

    private void changeFragment(Article article) {
        FragmentActivity activity = getActivity();
        if (activity != null) {
            FragmentManager fm = activity.getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            // 隐藏所有Fragment
            for (Fragment frag : fm.getFragments()) {
                if (frag != null && frag.isAdded()) {
                    transaction.hide(frag);
                }
            }
            Fragment existingFragment = fm.findFragmentByTag("ArticleFragment");

            if (existingFragment != null) {
                ((ArticleFragment) existingFragment).reclick(article);
                transaction.show(existingFragment);
            } else {
                Fragment articleFragment = new ArticleFragment();
                ((ArticleFragment) articleFragment).setArticle(article);
                transaction.add(R.id.FragmentContainer, articleFragment, "ArticleFragment");
            }
            transaction.commit();
        }
    }

    public void loadArticles(String type) {
        // 创建适配器并设置给 RecyclerView
        if (type.equals("like")) {
            progressIndicator.setVisibility(View.VISIBLE);
            getLikeOrStartArticles(getLikeArticleUrl, "like");

        } else if (type.equals("star")) {
            progressIndicator.setVisibility(View.VISIBLE);
            getLikeOrStartArticles(getStarArticleUrl, "star");
        }
    }


    private void initViews(View view) {
        btnLike = view.findViewById(R.id.fragment_like_or_star_button_like);
        btnStar = view.findViewById(R.id.fragment_like_or_star_button_star);
        progressIndicator = view.findViewById(R.id.fragment_like_or_star_progress_indicator);
        recyclerView = view.findViewById(R.id.fragment_like_or_star_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }
    public void getLikeOrStartArticles(String url, String type) {
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        // 创建请求体
        JSONObject json = new JSONObject();
        try {
            json.put("username", username);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        RequestBody requestBody = RequestBody.create(
                json.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );

        // 创建请求
        Request request = new Request.Builder()
                .url(url)  // 替换为实际服务器地址
                .post(requestBody)
                .build();

        // 异步发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                try {
                    String responseData = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseData);

                    if (jsonResponse.has("error")) {
                        String error = jsonResponse.getString("error");
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
                        });
                        return;
                    }

                    JSONArray articlesJson = jsonResponse.getJSONArray("articles");
                    List<Article> articleList = new ArrayList<>();

                    for (int i = 0; i < articlesJson.length(); i++) {
                        JSONObject articleJson = articlesJson.getJSONObject(i);

                        // 解析作者信息
                        JSONObject authorJson = articleJson.getJSONObject("author");
                        User author = new User(
                                authorJson.getString("name"),
                                authorJson.getString("avatar_url"),
                                authorJson.getString("level")
                        );

                        // 创建文章对象
                        Article article = new Article(
                                articleJson.getInt("article_id"),
                                articleJson.getString("title"),
                                articleJson.getString("content"),
                                articleJson.getString("image"),  // 图片URL
                                articleJson.getString("audio"),  // 音频URL
                                author,
                                articleJson.getString("create_time"),
                                articleJson.optInt("thumbs_up_numbers"),
                                articleJson.optInt("collect_numbers"),
                                null  // comments - 服务器返回中没有此字段
                        );

                        // 设置是否有音频
                        // 这里假设如果音频URL不为空，则有音频
                        if (articleJson.getString("audio")!= "null") {
                            article.setHaveAudio(true);
                        } else {
                            article.setHaveAudio(false);
                        }

                        articleList.add(article);
                    }

                    // 处理获取到的文章列表
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "获取成功", Toast.LENGTH_SHORT).show();

                        if (type.equals("like")) {
                            articleLikeList = articleList;
                            adapter = new LikeOrStartAdapter(articleLikeList, "like");
                            adapter.setOnItemClickListener(article -> {
                                // 处理点击事件
                                changeFragment(article);
                            });
                            recyclerView.setAdapter(adapter);
                        } else if (type.equals("star")) {
                            articleStarList = articleList;
                            adapter = new LikeOrStartAdapter(articleStarList, "star");
                            adapter.setOnItemClickListener(article -> {
                                // 处理点击事件
                                changeFragment(article);
                            });
                            recyclerView.setAdapter(adapter);
                        }
                        progressIndicator.setVisibility(View.GONE);

                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "数据解析错误", Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }
}
